<template>
  <!-- 文章列表组件 -->
  <div class="article_list">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" :success-text="tipText" :success-duration='1500'>
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :error.sync="error"
        error-text="请求失败，点击重新加载">
        <ArticleItem v-for="item in list" :key="item.art_id + ''" :article='item' />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticlesList } from '@/api/article.js'
import ArticleItem from '@/components/article-item/index.vue'
export default {
  props: {
    // 频道的id
    channelId: {
      type: Number,
      require: true
    }
  },
  data () {
    return {
      // 列表数据
      list: [],
      // 加载中状态
      loading: false,
      // 是否加载下一页数据
      finished: false,
      // 时间戳
      pre_timestamp: Date.now(),
      // 下拉刷新loading
      refreshing: false,
      // 底部报错提示
      error: false,
      // 刷新提示消息
      tipText: ''
    }
  },
  methods: {
    // 获取数据
    async onLoad () {
      if (this.refreshing) {
        this.list = []
        this.refreshing = false
      }
      try {
        const { data: res } = await getArticlesList({
          channel_id: this.channelId,
          // 获取第一页数据传当前时间戳
          timestamp: this.pre_timestamp,
          with_top: 0
        })
        this.list.push(...res.data.results)
        this.pre_timestamp = res.data.pre_timestamp
        this.loading = false
        if (res.data.results.length === 0) {
          this.finished = true
        }
      } catch (err) {
        this.error = true
      }
    },
    // 下拉刷新
    async onRefresh () {
      try {
        const { data: res } = await getArticlesList({
          channel_id: this.channelId,
          // 获取第一页数据传当前时间戳
          timestamp: Date.now(),
          with_top: 0
        })
        this.list.unshift(...res.data.results)
        this.refreshing = false
        this.tipText = '刷新成功,共加载' + res.data.results.length + '数据'
      } catch (err) {
        this.refreshing = false
        this.tipText = '刷新失败请重试'
      }
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {
    ArticleItem
  },
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
// 滚动条
.article_list {
  height: 100vh;
  overflow-y: scroll;
}
</style>
